#include "head.h"

char ip[64] = {0};
char port[32] = {0};
char token[512] = {0};
char name[64] = {0};

int main(int argc, char *argv[])
{
    //读取配置文件
    config  *config_info = (config *)malloc(sizeof(config));
    bzero(config_info,sizeof(config_info));
    int ret = read_config("./config.ini",config_info);
    if(ret == 0) {
        printf("配置文件读取失败\n");
        exit(0);
    }
    //初始化日志
    INIT_LOG(config_info -> log_path);


    bool is_connect = 0;
    int socket_fd = 0;
    shared_resource_t shared_resource;
    pool_data_t pool_data;
    client_init(config_info,&shared_resource, &is_connect, &pool_data, &socket_fd);


    // 登录注册的逻辑，这里获取正确的token
    account(&socket_fd,token, &is_connect);
    printf("%s@",name);
    fflush(stdout);


    // epoll相关
    int epoll_fd = epoll_create(10);
    epoll_add(epoll_fd, STDIN_FILENO);
    epoll_add(epoll_fd, socket_fd);

    while (1)
    {
        struct epoll_event events[2];
        bzero(events, sizeof(struct epoll_event) * 2);
        int epoll_num = epoll_wait(epoll_fd, events, 2, -1);
        for (int i = 0; i < epoll_num; i++)
        {
            if (events[i].data.fd == socket_fd)
            {
                //printf("\n");
                if(!socket_handler(socket_fd, &is_connect, epoll_fd)){
                    printf("%s@",name);
                    fflush(stdout);
                }              
                continue;
            }
            if(events[i].data.fd == STDIN_FILENO){
                // 判断服务端有没有把我踢掉,踢掉重新建立连接
                if(is_connect == 0)
                {
                    tcp_init(&socket_fd,ip,port);
                    epoll_add(epoll_fd, socket_fd);
                    is_connect = 1;
                }
                if(stdin_handler(socket_fd, &shared_resource)){
                    printf("%s@",name);
                    fflush(stdout);
                }               
            }
        }
    }
}
